<?php

namespace app\api\controller;

use app\common\model\AdminModel;
use Firebase\JWT\JWT;
use think\Controller;
use think\Request;

class Login extends Cross
{
    public function login(Request $request){
        ///获得前端数据
        $username = $request->param("username");
        $password = $request->param("password");
        // 建立数据库示图对象
        $admin = new AdminModel();
        /// status为0表示正常， 1为禁用
        $info = $admin->where("status", 0)->where("username", $username)->find();
        if(!$info){  //找不到
            return json(["code"=>0, "msg"=>"账号不存在"]);
        }
        //  密码是否匹配      echo md5($password);
        if($info['password'] != $password){
            return json(['code'=>0, 'msg'=>'账号或者密码错误']);
        }
        //   产生token    jwt:json web token
        $jwt = new JWT();
        $key = "api123456";
        $payload = [
            'iss' => 'http://127.0.0.1/php_big_project/api/public/', //iss: jwt签发者
            'aud' => 'http://127.0.0.1/php_big_project/api/public/', //aud: 接收jwt的一方
            'iat' => time(),  //iat: jwt的签发时间
            'nbf' => time(), //nbf: 定义在什么时间之前，该jwt都是不可用的.
            'aid' => $info['id']
        ];
        $token = $jwt::encode($payload, $key, 'HS512');

        return json(['code'=>1, 'msg'=>'登录成功', 'token'=>"$token",'nickname'=>$info['nickname'],
            'username'=>$username,"role"=>$info['role'], 'userid'=>$info['id'],'img'=>$info['img']]);
    }
    // public function register(){
    // }
}
